const jwt = require("jsonwebtoken");
const { JWT_SECRET } = require("../config/config.default");
const {
  tokenExpiredError,
  jsonWebTokenError,
  hadNotAdminPerimisson,
} = require("../constants/err.type");

// TOKEN 验证
const auth = async (ctx, next) => {
  const { authorization } = ctx.request.header;
  const token = authorization.replace("Bearer ", "");

  try {
    // user包含payload信息（id, user_name, is_admin）
    const user = jwt.verify(token, JWT_SECRET);
    // 保存变量中待controller调用
    ctx.state.user = user;
  } catch (error) {
    switch (error.name) {
      case "TokenExpiredError":
        console.error("token过期");
        return ctx.app.emit("error", tokenExpiredError, ctx);
      case "JsonWebTokenError":
        console.error("无效token");
        return ctx.app.emit("error", jsonWebTokenError, ctx);
    }
  }

  await next();
};

const hadAdminPermission = async (ctx, next) => {
  const { is_admin } = ctx.state.user;
  console.log(is_admin, "is_admin");
  if (!is_admin) {
    console.error("没有管理员权限");
    return ctx.app.emit("error", hadNotAdminPerimisson, ctx);
  }

  await next();
};

module.exports = {
  auth,
  hadAdminPermission,
};
